package com.gtd.ws

import grails.converters.*

import com.gtd.util.HashMapToXML
/**
 * This class is used for render content
 */
class Renderer {


	/**
	 * render: Render response with suitable format
	 *
	 * @param controller Controller
	 * @param res LinkedHashMap
	 * @return void
	 * @since 1.0
	 */
	static render(controller, res) {
    def ts = System.currentTimeMillis()
    def GMTTime = new Date().toGMTString()
    def rest_action = controller.params.rest_action
    if (!rest_action) {
      rest_action = ""
    } else {
      rest_action = "/" + rest_action
    }
    def data = [
      rest: [
        header: [
          uri: "/rest/" + controller.controllerName + rest_action,
          method: controller.request.method.toString(),
          code: "200", // Should change accordingly
          requestTime: [
            timestamp: ts.toString(),
            GMTTime: GMTTime.toString()
          ]
        ],
        body: res
      ]
    ]
    def format = controller.request.format
		//Default --request POST: request.format = form.
		//Change to xml
		if (format.equals("form")) {
      format = "xml"
		}
    if (format == null || format == "") {
      format = "xml"
    }
		//Display
		if (format.equals("xml")) {
      //controller.render data
      controller.response.contentType = "text/xml"
      def xml = HashMapToXML.convert(data)
      def xmlDef = """<?xml version="1.0" encoding="UTF-8"?>"""
      controller.render xmlDef + "\n" + xml
      
		} else if (format.equals("json")) {
      controller.render data as JSON
		} else if (format.equals("rss")) {
      //TODO: handle rss
		} else if (format.equals("atom")) {
      //TODO: handle atom
		} else {
      //TODO:
		}
	}
}
